package com.codefish.codefishseckill.service.impl;

import com.codefish.codefishseckill.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/09/13 下午 06:04
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {
    private static final String COMPANY_NAME = "codefish秒杀系统";

    @Resource
    private JavaMailSender mailSender;
    @Autowired
    TemplateEngine templateEngine;


    @Override
    public boolean sendCaptcha(String captchaCode, String destMailAddress) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        Context context = new Context();
        context.setVariable("receiver", destMailAddress);
        context.setVariable("code", captchaCode);
        String htmlStr = templateEngine.process("mail-template/captchaTmp", context);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(COMPANY_NAME + "<434426082@qq.com>");
            helper.setTo(destMailAddress);
            helper.setSubject("登录/注册验证码");
            helper.setText(htmlStr, true);
            mailSender.send(helper.getMimeMessage());
            return true;
        } catch (MessagingException e) {
            log.error("发送验证码邮件失败，原因：{}", e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

}
